//
//  RCCommunicationController.m
//  CoreLocationTest
//
//  Created by Miles on 10-05-11.
//  Copyright 2010 Miles Thorogood
//  greenmeat.net. All rights reserved.
//

#import "RCCommunicationController.h"
#import "RCConectionHandler.h"
#import "RCLocationHandler.h"
#import "TouchXML.h"
#import "RCMapViewController.h"


@interface RCCommunicationController() 
-(void) getDataFromServ ;
- (void) parseData ;
@end

@implementation RCCommunicationController

@synthesize receivedData ;
@synthesize location ;
@synthesize mediaDictionary ;
@synthesize locationHandler ;

-(id) init {
	self = [super init] ;
	if (self) {
		self.locationHandler = [[RCLocationHandler alloc] initWithDelegate:self] ; // this remains running in the background
		NSString *temp = @"";
		mediaDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
						   temp, @"audio",
						   temp, @"image",
						   temp, @"text",
						   nil] ;
	}
	return self ;
}
	
- (id)initWithDelegate:(id)del {
    if (self = [super init]) {
        // Custom initialization
		mapDelegate = del;
		
		self.locationHandler = [[RCLocationHandler alloc] initWithDelegate:self] ; // this remains running in the background
		NSString *temp = @"";
		mediaDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
						   temp, @"audio",
						   temp, @"image",
						   temp, @"text",
						   temp, @"ad",
						   temp, @"location",
						   temp, @"type", 
						   temp, @"error",
						   nil] ;
		
    }
    return self;
}


- (void) dealloc {
	[receivedData release] ;
	[location release] ;
	[mediaDictionary release] ;
	[locationHandler release] ;
	[super dealloc] ;	
}
	
// called from the location notification received delegate
-(void) getDataFromServ {
	
	NSString *postURL = [[[NSString alloc] initWithFormat:@"http://carr/stw/adapi/?publisher=280&lat=%+.6f&lon=%+.6f", 
						 location.coordinate.latitude, location.coordinate.longitude] autorelease];

	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];  
	[request setURL:[NSURL URLWithString:postURL]];   
	
	RCConectionHandler *handler = [[RCConectionHandler alloc] initWithDelegate:self];
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:handler];
	
}

- (void) parseData {
	//	we will put parsed data in an a array
	CXMLDocument *doc	= [[[CXMLDocument alloc] initWithData:self.receivedData options:0 error:nil] autorelease];
	NSString *audioURL;
	NSArray *nodes = NULL;
	//	searching for ad nodes
	nodes = [doc nodesForXPath:@"//ad" error:nil];
	
	// parse xml and add to our media dictionary
	for (CXMLElement *node in nodes) {
		int counter;
		for(counter = 0; counter < [node childCount]; counter++) {
			//	common procedure: dictionary with keys/values from XML node
			if ([[node childAtIndex:counter] stringValue]) {

				if ([[[node childAtIndex:counter] name] isEqualToString:@"code"]) {
					audioURL = [[node childAtIndex:counter] stringValue];
					NSLog(@"audio URL = %@", audioURL) ;
					NSArray *seperate = [audioURL componentsSeparatedByString:@", "] ;
					for (int i=0; i<[seperate count]; i++) {
						NSString *file = [seperate objectAtIndex:i] ;
						//NSLog(@"count %d = %@", i, file) ;
						NSString *extension = [file pathExtension] ;
						//NSLog(@"extension %d = %@", i, extension) ;
						if ([extension isEqualToString:@"mp3"] ) [mediaDictionary setObject:file forKey:@"audio"] ;
						if ([extension isEqualToString:@"png"] ) [mediaDictionary setObject:file forKey:@"image"] ;
						if ([extension isEqualToString:@"txt"] ) [mediaDictionary setObject:file forKey:@"text"] ;
						
					}
					
					//NSLog(@"audio = %@", [mediaDictionary objectForKey:@"audio"]) ;
					//NSLog(@"image = %@", [mediaDictionary objectForKey:@"image"]) ;
					//NSLog(@"text = %@", [mediaDictionary objectForKey:@"text"]) ;
				} // end if code
			
				// get and store ad id
				if ([[[node childAtIndex:counter] name] isEqualToString:@"clickUrl"]) {
					NSString *clickUrl = [[node childAtIndex:counter] stringValue];
					NSArray *chunks = [clickUrl componentsSeparatedByString:@"&"] ;
					for (int l=0; l<[chunks count]; l++) {
						NSString *result = [chunks objectAtIndex:l] ;
						//NSLog(@"chunks = %@", result) ;
						
						NSArray *miniChunks = [result componentsSeparatedByString:@"="] ;
						if ([miniChunks count] > 1) {
							if ([[miniChunks objectAtIndex:0] isEqualToString:@"ad"]) {
								[mediaDictionary setObject:[miniChunks objectAtIndex:1] forKey:@"ad"] ;
							}
						}
						//for (int m=0; m<[miniChunks count]; m++) {
						//	NSLog(@"chunks = %@", [miniChunks objectAtIndex:m]) ;
						//}
					}
				} // end if clickurl
				if ([[[node childAtIndex:counter] name] isEqualToString:@"adResponse"]) {
					NSString *type = [[node childAtIndex:counter] stringValue] ;
					[mediaDictionary setObject:type forKey:@"type"] ;
				}
			} // end if childAtIndex:counter
		} // end for counter 
	} // end for nodes
	
	[(RCMapViewController *) mapDelegate locationDataReceived:self];
}

// from RCCommunicationHandler
-(void)dataReceivedNotification:(id)handler {
	self.receivedData = [handler dataReceived];
	[handler release];
	[self parseData] ;

}

// from RCLocationHandler
-(void)locationReceivedNotification:(id)handler {
	self.location = (CLLocation *)[handler aLocation];
	//[handler release];
	[mediaDictionary setObject:self.location forKey:@"location"] ;
	[self getDataFromServ] ;
}

@end
